
import { readFileSync, writeFileSync } from 'fs';
import path from 'path';
import { BasePlatform } from '../platforms/BasePlatform';
import { AutoUploadPlatform, ChannelToName, channelToName, EPlatform } from '../platforms/PlatformConfig';
import { DingdingBot } from '../utils/DingdingBot';
let originPlatformId: number = 1;
export function beforeStartBuild(options: {
    channel: string,//渠道
    projectDir: string,//工程目录
    platformsInfo: any,//渠道信息
    isDebug?: boolean,//是否是测试版本
}, callback: Function) {
    //构建前工作
    let launcherscene = path.join(options.projectDir, "assets/scene/Launcher.fire");
    let launcher: Object[] = JSON.parse(readFileSync(launcherscene, { encoding: 'utf-8' }));
    for (let i = 0, len = launcher.length; i < len; i++) {
        let obj = launcher[i];
        if (obj.hasOwnProperty('CustomPlatform')) {
            //@ts-ignore
            originPlatformId = obj['CustomPlatform'];
            //@ts-ignore
            obj['CustomPlatform'] = EPlatform[options.channel];
            if (obj.hasOwnProperty("testMode")) {
                //@ts-ignore
                obj['testMode'] = !!options.isDebug;
            }
            writeFileSync(launcherscene, JSON.stringify(launcher, null, "\t\t"), { encoding: 'utf8' });
            break;
        }
    }

    callback();
}

export function afterBuildFinish(options: {
    platform: BasePlatform
}, callback: Function) {
    let pl = options.platform;
    if (pl.configData.notifyDingTalk && pl.configData.dingTalkWebHook) {
        let version = pl.version;
        let channelName = channelToName[pl.curPackChannel];
        let bot = new DingdingBot(pl.configData.dingTalkWebHook);
        let outputPath = AutoUploadPlatform[pl.curPackChannel] ? (channelName + "后台") : (pl.curPackChannel == 'web_mobile' ? `[${channelName}链接](${pl.channelInfo.serverPath})` : pl.outputPath.substr(2));
        let msg = `#### 游戏名字：**<font color='#1E90FF'>${pl.configData.gameName}</font>** \n ##### 游戏渠道：**${channelName}**\n ##### 游戏版本：**${version}** \n ##### 打包状态：**<font color='#00dd00'>完成</font>** \n ##### 资源包路径：${outputPath} \n ##### 打包时间：**${new Date().toLocaleString()}** \n`;
        let title = `${pl.configData.gameName}打包通知`;
        bot.pushMsgMarkdown(msg, title);
    }
    //构建完成后工作
    callback();
}